// src/chat.js
import { tim, TIM } from '@/tim'

// 发送消息
export const sendMessage = async ({ toId, content, type = 'text', toUserName }) => {
  try {
    // 创建消息实例，可以在这里添加自定义字段
    let message = tim.createTextMessage({
      to: toId,
      conversationType: TIM.TYPES.CONV_C2C,
      payload: { 
        text: content,
        toUserName: toUserName 
      }
    })

    // 发送消息
    const result = await tim.sendMessage(message)
    return {
      code: 0,
      data: {
        message: result.data.message
      }
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    return {
      code: -1,
      message: error.message
    }
  }
}

// 监听新消息
export const listenMessages = (callback) => {
  const handleMessage = (event) => {
    const messageList = event.data
    messageList.forEach((message) => {
      callback({
        id: message.ID,
        content: message.payload?.text || '',
        fromId: message.from,
        timestamp: message.time * 1000,
        type: message.type,
        avatar: message.avatar
      })
    })
  }

  tim.on(TIM.EVENT.MESSAGE_RECEIVED, handleMessage)
  
  return () => {
    tim.off(TIM.EVENT.MESSAGE_RECEIVED, handleMessage)
  }
}

// 获取当前用户ID
export const getCurrentUserID = async () => {
  try {
    const profile = await tim.getMyProfile()
    return profile.data?.userID
  } catch (error) {
    console.error('获取用户ID失败:', error)
    return null
  }
}
